package com.woke.addressactivity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.WriterException;
import com.http.HttpMethods;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.woke.method.MyApp;
import com.woke.serizedatas.Datas_load;
import com.zhongcai.online.R;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;
import cn.xl.xxl.imagecache.ImageLoader;

/**
 * 具体推广码的 二维码
 */
public class UserpromoteIIActivity extends Activity {

    private ImageView mIcon;
    private ImageView mIermae;
    private TextView mTadd, mTname, mTitle, mTshare;
    private MyApp myapp;
    private Datas_load loaded;
    private ImageLoader imageLoader;
    private int screenHigth, screenWidth;
    private Intent intent;
    private String titleString;
    private String url;
    // 分享
    private ClipData myClip;
    private ClipboardManager myClipboard;
    //	public static String TEST_IMAGE;
//	private static final String FILE_NAME = "/ic_icon2.jpg";
    private int mOrgId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_userinfo_er);
        imageLoader = new ImageLoader(this);
        myapp = (MyApp) getApplication();
        screenHigth = myapp.screenHigth;
        screenWidth = myapp.screenWidth;
//		new Thread() {
//			public void run() {
//			initImagePath();
//			}
//			}.start();

        findViewById(R.id.user_er_back).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });

        mIcon = (ImageView) findViewById(R.id.user_er_imgeicon);
        mIermae = (ImageView) findViewById(R.id.user_er_imger);
        mTadd = (TextView) findViewById(R.id.user_er_textadd);
        mTname = (TextView) findViewById(R.id.user_er_textname);
        mTitle = (TextView) findViewById(R.id.fmuser_text_title);
        myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
        mTshare = (TextView) findViewById(R.id.avhtml_text_share);
        mTshare.setVisibility(View.VISIBLE);
        mTshare.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Auto-generated method stub
                showShare();
            }
        });

        intent = getIntent();
        titleString = intent.getStringExtra("title");
        mOrgId = intent.getIntExtra("orgid", -1);
        mTitle.setText(titleString);
        LayoutParams params = mIermae.getLayoutParams();
        params.width = screenWidth / 5 * 4;
        params.height = screenWidth / 5 * 4;
        mIermae.setLayoutParams(params);
        if (myapp.getDatas_load() != null && null != myapp.getDatas_load().getProvince_id()
                && !myapp.getDatas_load().getProvince_id().equals("")) {
            mTadd.setText(myapp.getDatas_load().getProvince_id() + " "
                    + myapp.getDatas_load().getCity_id());
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        loaded = myapp.getDatas_load();
        if (null != loaded) {
            mTname.setText(loaded.getUser_nicename());
            if (!TextUtils.isEmpty(loaded.getAvatar())) {
                imageLoader.DisplayImage("http://" + loaded.getAvatar(), mIcon,
                        false, true, false, 0);
            }


        }
        String typeString;
        if (titleString.equals("中财推广")) {
            typeString = "Promocode";
        } else {
            typeString = "IdPromocode";
        }
        if (!TextUtils.isEmpty(loaded.getId())) {
            Log.e("mOrgId.........",""+mOrgId);
            getmyerweima(typeString);
        }
    }

    private void getmyerweima(String typeString) {
        if (mOrgId == -1) return;
        AsyncHttpClient ahc = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("g", "api");
        params.put("m", "user");
        //		params.put("a", typeString);
        params.put("a", "promocodeDetail");

        params.put("userid", myapp.getDatas_load().getId());
        params.put("orgid", mOrgId);

        ahc.get(HttpMethods.BASEURL, params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers,
                                  JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("onSuccess" + myapp.getDatas_load().getId(), "--" + response);
                try {
                    String flag = response.getString("flag");
                    if (flag.equals("success")) {
                        JSONObject jsonObject = response.getJSONObject("data");
                        JSONObject jsonObject2 = jsonObject
                                .getJSONObject("data");
                        String string = jsonObject2.getString("code");
                        // {"flag":"success","info":"操作成功","data":{"data":{"code":"app.88china.com:8384\/data\/upload\/qrcode\/be11f3301dbaba5d.png","url":"http:\/\/app.88china.com:8384\/index.php?g=api&m=Register&a=index&type=1&invitation_code=18759266591"}},"time":1483526253}
                        Log.e("UserPromote", string);
                        url = jsonObject2.getString("url");
                        System.out.println(string);
                        if (null != url && !url.equals("")) {
//							imageLoader.DisplayImage("http://" + string,
//									mIermae, false, false, false, 0);
                            if (!isFinishing()) {
                                //								Glide.with(Userinfo_erActivity.this)
                                //										.load("http://" + string)
                                //										.into(mIermae);

                                try {
                                    Bitmap qrCodeBitmap = EncodingHandler.createQRCode(url, 350);
                                    mIermae.setImageBitmap(qrCodeBitmap);
                                } catch (WriterException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers,
                                  String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
            }

            @Override
            public void onStart() {
                super.onStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        imageLoader.clearCache();
        imageLoader.clearMemoryCache();
        super.onDestroy();
    }

    /*private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        // 参考代码配置章节，设置分享参数
        // 构造一个图标
        Bitmap enableLogo = BitmapFactory.decodeResource(getResources(),
                R.drawable.ssdk_oks_logo_fuzhi);
        String label = "复制链接";
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                myClip = ClipData.newPlainText("text", url);
                myClipboard.setPrimaryClip(myClip);
                Toast.makeText(getApplicationContext(), "已复制到剪贴板",
                        Toast.LENGTH_SHORT).show();
            }
        };
        // oks.show(HtmlActivity.this);
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();
        // oks.addHiddenPlatform(label);
        oks.setCustomerLogo(enableLogo, enableLogo, label, listener);
        // oks.setViewToShare(enableLogo);
        // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
        // oks.setNotification(R.drawable.ic_launcher,
        // getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("中财在线-中国领先的移动金融平台");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText("零元创业，年赚百万!\n成为中财在线全国推广商享受更多优惠政策");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath(TEST_IMAGE);// 确保SDcard下面存在此张图片
        oks.setImagePath("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        // oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("成为中财在线全国推广商享受更多优惠政策");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);

        // 启动分享GUI
        oks.show(this);
    }*/
    private void showShare() {
//        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        // 参考代码配置章节，设置分享参数
        // 构造一个图标
        Bitmap enableLogo = BitmapFactory.decodeResource(getResources(), R.drawable.ssdk_oks_logo_fuzhi);
        String label = "复制链接";
        OnClickListener listener = new OnClickListener() {
            public void onClick(View v) {
                myClip = ClipData.newPlainText("text", url);
                myClipboard.setPrimaryClip(myClip);
                Toast.makeText(getApplicationContext(), "已复制到剪贴板",
                        Toast.LENGTH_SHORT).show();
            }
        };
        oks.setTheme(OnekeyShareTheme.CLASSIC);
//		 oks.show(HtmlActivity.this);
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
//		 oks.addHiddenPlatform(label);
        oks.setCustomerLogo(enableLogo, label, listener);
//		 oks.setViewToShare(enableLogo);
        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(getResources().getString(R.string.oem_title_tuijian_share));
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl(url);
        // text是分享文本，所有平台都需要这个字段
        oks.setText("刷卡0.28%秒到！分润秒结！\n中交所网贷50万实时秒批！\n每天超过1万人加入推广商！");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImageUrl(getResources().getString(R.string.oem_url_tuijian_share));
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl(url);
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment(getResources().getString(R.string.app_name));
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getResources().getString(R.string.oem_title_tuijian_share));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl(url);
        oks.setVenueName(getResources().getString(R.string.app_name));
        // 启动分享GUI
        oks.show(this);
    }
//	private void initImagePath() {
//		try {
//		if (Environment.MEDIA_MOUNTED.equals(Environment
//		.getExternalStorageState())
//		&& Environment.getExternalStorageDirectory().exists()) {
//		TEST_IMAGE = Environment.getExternalStorageDirectory()
//		.getAbsolutePath() + FILE_NAME;
//		} else {
//		TEST_IMAGE = getApplication().getFilesDir().getAbsolutePath()
//		+ FILE_NAME;
//		}
//		// 创建图片文件夹
//		File file = new File(TEST_IMAGE);
//		if (!file.exists()) {
//		file.createNewFile();
//		Bitmap pic = BitmapFactory.decodeResource(getResources(),
//		R.drawable.ic_icon2);
//		FileOutputStream fos = new FileOutputStream(file);
//		pic.compress(CompressFormat.JPEG, 100, fos);
//		fos.flush();
//		fos.close();
//		}
//		} catch (Throwable t) {
//		t.printStackTrace();
//		TEST_IMAGE = null;
//		}
//		}
}
